import Vue from "vue";
import Vuex from "vuex";
import { setLang } from "../locales";
import { SET_LANG, SET_ACCOUNT, SET_TAG_NAVS, SET_BREAD_CRUMB } from "./types";
import storage from "../utils/storage";

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    lang: "",
    account: {},
    tagNavs: storage.getItem(SET_TAG_NAVS) || [],
    breadCrumb: []
  },
  mutations: {
    [SET_LANG](state, lang) {
      state.lang = lang;
    },
    [SET_ACCOUNT](state, account) {
      state.account = account;
    },
    [SET_TAG_NAVS](state, navs) {
      state.tagNavs = navs;
      storage.setItem(SET_TAG_NAVS, navs);
    },
    [SET_BREAD_CRUMB](state, breadCrumb) {
      state.breadCrumb = breadCrumb;
    }
  },
  actions: {
    setLang({ commit }, lang) {
      setLang(lang);
      commit(SET_LANG, lang);
    },
    async setTagNavs({ commit, state }, route) {
      const tagNavs = [...state.tagNavs];

      const index = tagNavs.findIndex(item => item.name === route.name);

      if (index > -1) {
        tagNavs.splice(index, 1, route);
      } else {
        tagNavs.push(route);
      }

      commit(SET_TAG_NAVS, tagNavs);
    },
    removeTagNav({ commit, state }, route) {
      const tagNavs = [...state.tagNavs];

      const index = tagNavs.findIndex(item => item.name === route.name);

      tagNavs.splice(index, 1);

      commit(SET_TAG_NAVS, tagNavs);
    },
    async setBreadCrumb({ commit }, breadCrumb) {
      commit(SET_BREAD_CRUMB, breadCrumb);
    }
  },
  getters: {
    lang: state => state.lang,
    account: state => state.account,
    tagNavs: state => state.tagNavs,
    breadCrumb: state => state.tagNavs
  },
  modules: {}
});
